import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { CommonModal } from "@/views/components/CommonModal";
import CommonTable from "@/pages/OrderModule/common/components/CommonTable/components/CommonTable";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { Button, Form, Radio, Select, message } from "antd";
import { useState, useEffect } from "react";
import FormRowWrapper from "../FormRowWrapper";
import SelectPackaging from "./SelectPackaging";
import CommonZjfImg from "@/components/CommonImg/ZifComponent";
import { packagingStrategySaveOp, packagingStrategyGetById, updatePackagingStrategyOp, warehouseSelectList } from "../../service";
import { isEmpty, find } from "lodash";
import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import CommonLoading from "@/components/CommonLoading";
import SelectTag from "@/components/SelectTag";
import IconFont from "@/components/IconFont";
import SelectShop from "@/components/SelectShop";
import GoodsSelectModal from "@/pages/OrderModule/common/bizcomponents/GoodsSelectModal";
import BatchInputModal from "@/pages/OrderModule/common/components/BatchInputModal2";
import { labelTypeMap, labelColorMap } from "@/utils/config";
import { getAllowClearProps } from "../../helpers/constant";

//弹窗标题
const titleMap = {
	add: "新增",
	edit: "编辑"
};

const AddNewModal = ({ visible, type, recordData, handleCancel, handleOk }) => {
	const [packVisible, setPackVisible] = useState(false); //添加包装弹窗
	const [packList, setPackList] = useState([]); //包装list
	const [detailData, setDetailData] = useState({}); //详情数据
	const [labelVisible, setLabelVisible] = useState(false); //是否展示标签弹窗
	const [selectLabels, setSelectLabels] = useState([]); //选择订单标签
	const [shopVisible, setShopVisible] = useState(false); //店铺组件弹窗
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [warehouse, setWarehouse] = useState([]); //仓库下拉
	const [goodsSelectInfo, setGoodsSelectInfo] = useState({
		//新增商品弹窗
		type: "",
		name: "",
		visible: false,
		spuCodes: [],
		goodsCodes: [],
		notParticipateSpuCodes: [],
		notParticipateGoodsCodes: []
	});
	const [batchInfo, setBatchInfo] = useState({
		visible: false,
		label: "",
		name: ""
	}); //批量输入弹窗
	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	const goodsRange = Form.useWatch("goodsRange", form);

	useEffect(() => {
		if (visible) {
			form.resetFields();
			setPackList([]);
			getWarehouseSelectList();
			if (!isEmpty(recordData)) {
				getPackagingStrategyGetById();
			}
		}
	}, [visible, recordData]);

	useEffect(() => {
		if (!isEmpty(detailData)) {
			form.resetFields();
			setPackList([detailData.packageInfo]);
			if (detailData.labelConfigList) {
				setSelectLabels(detailData.labelConfigList);
			}
			if (detailData.ecStoreList) {
				setSelectShops(detailData.ecStoreList);
			}
		}
	}, [detailData]);

	useEffect(() => {
		if (selectLabels.length) {
			form.setFieldsValue({
				labelIds: selectLabels.map(item => (labelTypeMap[item.name] ? labelColorMap[item.name] : item.name)).join(",")
			});
		} else {
			form.setFieldsValue({ labelIds: "" });
		}
	}, [selectLabels]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	//智能包装详情
	const getPackagingStrategyGetById = async () => {
		setLoading(true);
		const { success, data = {} } = await packagingStrategyGetById({
			id: recordData.id
		});
		if (success) {
			setDetailData(data);
		}
		setLoading(false);
	};

	//仓库下拉选择
	const getWarehouseSelectList = async () => {
		setLoading(true);
		const { success, data = [] } = await warehouseSelectList();
		if (success) {
			setWarehouse(data.filter(item => item.isOpen));
		}
		setLoading(false);
	};

	const onFinish = values => {
		form
			.validateFields()
			.then(val => {
				packagingStrategySave(val);
			})
			.catch(err => {});
	};

	const onFinishFailed = errorInfo => {
		console.log("Failed:", errorInfo);
	};

	//新增/编辑智能b包装
	const packagingStrategySave = async val => {
		const { specifiedWarehouseIds } = val;
		if (packList.length) {
			let res;
			const params = {
				...val,
				labelIds: selectLabels.length > 0 ? selectLabels.map(item => item.id).join(",") : undefined,
				packageId: packList[0].goodsId,
				ecStoreIds: selectShops.length > 0 ? selectShops.map(item => item.id).join(",") : undefined,
				specifiedWarehouseIds:
					specifiedWarehouseIds && specifiedWarehouseIds.length > 0 ? specifiedWarehouseIds.join(",") : undefined
			};
			setLoading(true);
			if (type == "add") {
				res = await packagingStrategySaveOp(params);
			} else {
				params.id = recordData.id;
				res = await updatePackagingStrategyOp(params);
			}
			const { success, msg = "" } = res;
			if (success) {
				message.success(msg);
				handleOk();
			}
			setLoading(false);
		} else {
			message.info("包装不能为空");
		}
	};

	const baseTableColumns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "包装",
			dataIndex: "index",
			key: "index",
			width: 180,
			render: (t, record, i) => (
				<span>
					<div style={{ display: "flex" }}>
						<CommonZjfImg storeId={record.storeId} img={record.packageImage} />
						<div style={{ marginLeft: "8px" }}>
							<div>{record.packageName}</div>
							<div>{record.packageSize}</div>
						</div>
					</div>
				</span>
			)
		},

		{
			title: "商品编码",
			dataIndex: "goodsId",
			key: "goodsId",
			width: 100
		},
		{
			title: "款式编码",
			dataIndex: "goodsCommonid",
			key: "goodsCommonid",
			width: 100
		},
		{
			title: "价格",
			dataIndex: "packagePrice",
			width: 80,
			render(value, record) {
				return <span style={{ color: "#f00" }}>¥{value}</span>;
			}
		},
		{
			title: "数量(个)",
			width: 120,
			dataIndex: "goodsNum",
			key: "goodsNum",
			render(value, record) {
				return <span>{value || 1}</span>;
			}
		},
		{
			title: "操作",
			width: 120,
			dataIndex: "goodsNum",
			key: "goodsNum",
			render(value, record) {
				return (
					<Button onClick={() => setPackList([])} type="link" size="small">
						删除
					</Button>
				);
			}
		}
	];

    //清除店铺弹窗
    const handleClear = (e, code) => {
        const val = e.target.value;
        if(val == '') {
            if(code == 'store') {
                setSelectShops([]);
            } else {
			    setSelectLabels([]);
            }
        }
    }

	const showModal = (name, type) => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			type,
			name,
			visible: true
		});
	};

	//选择商品
	const handleGoodsSelect = data => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			[goodsSelectInfo.name]: data,
			visible: false
		});
		const val = ["spuCodes", "notParticipateGoodsCodes"].includes(goodsSelectInfo.name)
			? data.map(v => v.spuCode)
			: data.map(v => v.skuCode);
		form.setFieldsValue({
			[goodsSelectInfo.name]: val.join()
		});
	};

	//选择包装弹窗
	const SelectPackagingProps = {
		visible: packVisible,
		handleCancel() {
			setPackVisible(false);
		},
		handleOk(arr) {
			const list = [];
			arr.forEach(item => {
				list.push({
					packageName: item.goodsName,
					packageImage: item.goodsImage,
					packageSize: item.goodsSpec,
					packagePrice: item.goodsPrice,
					...item
				});
			});
			setPackVisible(false);
			setPackList(list);
		}
	};

	//标签弹窗
	const SelectTagProps = {
		selectLabels: selectLabels.map(item => item.id),
		showFilterMethod: false,
		handleCancel() {
			setLabelVisible(false);
		},
		handleDealData(selectTag, realData) {
			const arr = [];
			selectTag.forEach(item => {
				const obj = find(realData, ["id", item]);
				arr.push(obj);
			});
			return arr;
		},
		handleOK(val) {
			setLabelVisible(false);
			setSelectLabels(val);
		}
	};

	//店铺组件
	const SelectShopProps = {
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	//选择商品组件
	const changeGoodsModalProps = {
		hiddenGoodNum: true,
		type: goodsSelectInfo.type,
		hiddenExtra: goodsSelectInfo.type == "NoNumberInput" ? true : false,
		submitCallback(changedArr) {
			handleGoodsSelect(changedArr);
		},
		handleCancel() {
			setGoodsSelectInfo({
				...goodsSelectInfo,
				visible: false
			});
		},
		setSelectedRows(data, rowKey) {
			return goodsSelectInfo[goodsSelectInfo.name].map(v => v[rowKey]) || [];
		}
	};

	//批量输入弹窗
	const BatchInputModalProps = {
		...batchInfo,
		handleCancel() {
			setBatchInfo({
				...batchInfo,
				visible: false
			});
		},
		handleOk(val) {
			form.setFieldsValue({
				[batchInfo.name]: val
			});
			setBatchInfo({
				...batchInfo,
				visible: false
			});
		}
	};

	//仓库下拉多选
	const optionWarehouse =
		!isEmpty(warehouse) &&
		warehouse.map(d => (
			<Option key={d.id} value={d.id + ""}>
				{d.warehouseName}({d.isOpen ? "代发" : "自发"})
			</Option>
		));

	return (
		<>
			<CommonModal
				title={{ title: `${titleMap[type]}包装策略` }}
				open={visible}
				onCancel={handleCancel}
				width={834}
				destroyOnClose
				bodyStyle={{ height: 500, overflow: "auto" }}
				okText="保存"
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button key="save" htmlType="submit" onClick={onFinish} type="primary">
						保存
					</Button>
				]}
			>
				<Form
					name="basic"
					initialValues={{
						...detailData,
						status: detailData.status || detailData.status == 0 ? detailData.status : 1,
						goodsRange: detailData.goodsRange || 1,
						specifiedWarehouseIds: detailData.specifiedWarehouseIds ? detailData.specifiedWarehouseIds.split(",") : undefined
					}}
					form={form}
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete="off"
					layout="horizontal"
					labelAlign="right"
				>
					<SubTitle title="基本信息" as="s2" symbol />
					{FormRowWrapper([
						<Form.Item name="name" rules={[{ required: true, message: "必填，请输入包装策略名称" }]}>
							<CommonInput placeholder="必填，请输入包装策略名称" maxLength={30} showCount aria-required allowClear />
						</Form.Item>,
						<Form.Item
							name="level"
							rules={[
								{ required: true, message: "必填，请输入优先级" },
								{
									pattern: /^[1-9]\d*$/g,
									message: "请输入正整数"
								}
							]}
						>
							<CommonInputNumber placeholder="必填，优先级" aria-required min={1} max={100} allowClearProps={getAllowClearProps(form)} />
						</Form.Item>
					])}
					<Form.Item rules={[{ required: true, message: "必填，请选择是否启用" }]} name="status" label="是否启用">
						<Radio.Group>
							<Radio value={1}>启用</Radio>
							<Radio value={0}>禁用</Radio>
						</Radio.Group>
					</Form.Item>
					<SubTitle
						title={
							<>
								订单条件
								<span style={{ fontWeight: 300, fontSize: 12 }}>（不同条件之间需要都满足）</span>
							</>
						}
						as="s2"
						symbol
					/>

					{FormRowWrapper([
						<Form.Item name="ecStoreIds">
							<CommonInput
								// readOnly
								onClick={() => setShopVisible(true)}
                                allowClear
								placeholder="请选择店铺"
                                onChange={(e) => handleClear(e, 'store')}
								suffix={<IconFont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
							/>
						</Form.Item>,
						<Form.Item name="labelIds">
							<CommonInput
								// readOnly
                                allowClear
                                onChange={(e) => handleClear(e, 'orderTag')}
								onClick={() => setLabelVisible(true)}
								placeholder="请选择订单标签"
								suffix={<IconFont onClick={() => setLabelVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
							/>
						</Form.Item>,
						<Form.Item name="specifiedWarehouseIds">
							<Select mode="multiple" showSearch placeholder="请选择仓库" optionFilterProp="children" allowClear={true}>
								{optionWarehouse}
							</Select>
						</Form.Item>
					])}
					<Form.Item name="goodsRange" label="商品范围：">
						<Radio.Group>
							<Radio value={1}>所有商品</Radio>
							<Radio value={2}>指定商品</Radio>
						</Radio.Group>
					</Form.Item>
					<Form.Item label="以下3个字段是“或”的关系" colon={false} noStyle />
					{goodsRange == 2
						? FormRowWrapper([
								<Form.Item name="goodsNames">
									<BatchSuffixInput
										clearable
										allowClear
										autoMultiLine
										modalProps={{
											title: "批量输入"
										}}
										maxItem={500}
										placeholder="请输入包含商品名称关键词，多个逗号隔开"
										message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
										areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
									/>
								</Form.Item>,
								<Form.Item name="goodsCodes">
									{/* <BatchSuffixInput
								clearable
								allowClear
								autoMultiLine
								modalProps={{
									title: "批量输入"
								}}
								maxItem={500}
								placeholder="指定商品编码，多个逗号隔开"
								message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
								areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
							/> */}
									<CommonInput
										placeholder="请输入指定商品编码，多个商品编码逗号隔开"
										suffix={
											<>
												<IconFont type="iconmodal-input" onClick={() => showModal("goodsCodes", "AccordingStyle")} />
												<IconFont
													type="icondirect-input"
													onClick={() => setBatchInfo({ visible: true, label: "商品编码", name: "goodsCodes" })}
												/>
											</>
										}
									/>
								</Form.Item>,
								<Form.Item name="spuCodes">
									<CommonInput
										placeholder="请输入指定款式编码，多个款式编码逗号隔开"
										suffix={
											<>
												<IconFont type="iconmodal-input" onClick={() => showModal("spuCodes", "NoNumberInput")} />
												<IconFont
													type="icondirect-input"
													onClick={() => setBatchInfo({ visible: true, label: "款式编码", name: "spuCodes" })}
												/>
											</>
										}
									/>
								</Form.Item>
							])
						: ""}
					<SubTitle title="选择包装" as="s2" symbol />
					<Button onClick={() => setPackVisible(true)} style={{ margin: "8px 0 " }}>
						选择包装
					</Button>
					<CommonTable
						columns={baseTableColumns}
						dataSource={packList}
						pagination={false}
						scroll={{ y: 100 }}
						rowKey={"packageId"}
					/>
					<SelectPackaging {...SelectPackagingProps} />
				</Form>
				{labelVisible && <SelectTag {...SelectTagProps} />}
				{shopVisible && <SelectShop {...SelectShopProps} />}
				{goodsSelectInfo.visible && <GoodsSelectModal {...changeGoodsModalProps} />}
				{batchInfo.visible && <BatchInputModal {...BatchInputModalProps} />}
				<CommonLoading loading={loading} />
			</CommonModal>
		</>
	);
};
export default AddNewModal;
